<template>
  <div>
    <div
      ref="contextMenu"
      :style="menuStyle"
      v-show="visible"
      class="context-menu"
    >
      <a-menu @click="handleMenuClick">
        <a-menu-item key="copy" class="context-menu-item"
          >复制{{ isAllCopy ? `(全部)` : "" }}</a-menu-item
        >
        <a-menu-item
          key="copy_split"
          class="context-menu-item"
          v-if="isCopySplit"
          >复制(拆分)</a-menu-item
        >
        <a-menu-item key="paste" class="context-menu-item">粘贴</a-menu-item>
      </a-menu>
    </div>
    <paste-context ref="pasteContextRef" @ok="pasterContent"></paste-context>
  </div>
</template>

<script>
// import { copyToClipboard } from "@/views/workflow/WorkflowCanvas/nodeOutput/utils";
import _ from "lodash";
import { nanoid } from "nanoid";
import PasteContext from "@/components/Form/base/PasteContext.vue";
import { componentTypeFileName } from "@/components/Form/base/options";
import { Message } from "@arco-design/web-vue";
// 使用 Vite 的 import.meta.glob 预加载 formViews 下所有组件，便于动态按文件名导入
const formViewModules = import.meta.glob("../formViews/*.vue");

export default {
  name: "ContextMenu",
  components: { PasteContext },
  inject: ["dataObj"],
  computed: {
    isCopySplit() {
      return (
        this.dataObj.pageData?.[this.dataObj.selectIndex]?.formData.type ===
          "table" && !this.isAllCopy
      );
    },
  },
  data() {
    return {
      visible: false,
      isAllCopy: false,
      menuStyle: {
        position: "absolute",
        left: "0px",
        top: "0px",
        zIndex: 9999,
      },
      screenScale: 1, // 默认缩放倍数
    };
  },
  methods: {
    calculateScreenScale() {
      const screenWidth = window.screen.width;
      const screenHeight = window.screen.height;
      const baseWidth = 1920;
      const baseHeight = 1080;

      // 计算宽度和高度的缩放倍数
      const widthScale = screenWidth / baseWidth;
      const heightScale = screenHeight / baseHeight;

      // 取较小的那个作为最终的缩放倍数
      this.screenScale = Math.min(widthScale, heightScale);

      // console.log(`屏幕分辨率: ${screenWidth}x${screenHeight}`)
      // console.log(`相对于1080p的缩放倍数: ${this.screenScale.toFixed(2)}`)
    },
    show(event, index) {
      this.isAllCopy = !_.isNumber(index);
      this.menuStyle.left = `${event.clientX - 320 * this.screenScale}px`;
      this.menuStyle.top = `${event.clientY - 50}px`;
      this.visible = true;
      window.addEventListener("click", this.close);
    },
    close() {
      this.visible = false;
      window.removeEventListener("click", this.close);
    },
    // async handleMenuClick({ key }) {
    //   if (key === "copy") {
    //     if (this.isAllCopy) {
    //       // 复制全部组件
    //       const pageData = this.dataObj.pageData;
    //       // 调用复制函数
    //       copyToClipboard(JSON.stringify(pageData), this.$message);
    //     } else {
    //       // 复制单个组件
    //       const item = this.dataObj.pageData[this.dataObj.selectIndex];
    //       // 调用复制函数
    //       copyToClipboard(JSON.stringify(item), this.$message);
    //     }
    //   } else if (key === "copy_split") {
    //     // 表格拆分为多个组件
    //     const item = this.dataObj.pageData[this.dataObj.selectIndex];
    //     console.log(item.formData.columns, "拆分数据");
    //     const newItems = item.formData.columns
    //       .filter((column) => column.controlType !== "total")
    //       .map((column) => {
    //         const { controlType, cid, title, dataIndex, dataId } = column;
    //         if (controlType === "dataSource") {
    //           const fileName = componentTypeFileName["select"];
    //           const importer = formViewModules[`../formViews/${fileName}.vue`];
    //           if (!importer) {
    //             this.$message.error(`未找到组件文件: ${fileName}.vue`);
    //             return null;
    //           }
    //           const mod = await importer();
    //           const { defaultData } = mod;
    //           return {
    //             cid: cid,
    //             type: "select",
    //             name: title,
    //             isSendData: true,
    //             icon: "",
    //             formData: Object.assign({}, defaultData(), {
    //               ...column,
    //               name: title,
    //               dataIndex: dataIndex,
    //               notMod: false,
    //               controlType: "1",
    //               dataSource: "dataSource",
    //               dataSourceId: dataId,
    //             }),
    //           };
    //         } else if (controlType === "sourceKey") {
    //           const fileName = componentTypeFileName["input"];
    //           const importer = formViewModules[`../formViews/${fileName}.vue`];
    //           if (!importer) {
    //             this.$message.error(`未找到组件文件: ${fileName}.vue`);
    //             return null;
    //           }
    //           const mod = await importer();
    //           const { defaultData } = mod;
    //           return {
    //             cid: cid,
    //             type: "input",
    //             name: title,
    //             isSendData: true,
    //             icon: "",
    //             formData: Object.assign({}, defaultData(), {
    //               ...column,
    //               name: title,
    //               dataIndex: dataIndex,
    //               notMod: false,
    //               controlType: "1",
    //             }),
    //           };
    //         } else {
    //           const fileName = componentTypeFileName[controlType];
    //           const importer = formViewModules[`../formViews/${fileName}.vue`];
    //           if (!importer) {
    //             this.$message.error(`未找到组件文件: ${fileName}.vue`);
    //             return null;
    //           }
    //           const mod = await importer();
    //           const { defaultData } = mod;
    //           return {
    //             cid: cid,
    //             type: controlType,
    //             name: title,
    //             isSendData: true,
    //             icon: "",
    //             formData: Object.assign({}, defaultData(), {
    //               ...column,
    //               name: title,
    //               dataIndex: dataIndex,
    //               notMod: false,
    //               controlType: "1",
    //             }),
    //           };
    //         }
    //       });
    //     const filteredItems = newItems.filter(Boolean);
    //     console.log(filteredItems, "表格拆分");
    //     // 调用复制函数
    //     copyToClipboard(JSON.stringify(filteredItems), this.$message);
    //   } else if (key === "paste") {
    //     // 粘贴逻辑
    //     this.pasteFromClipboard();
    //   }
    //   this.close();
    // },
    // 最小可用版本，避免方法缺失导致报错
    handleMenuClick({ key }) {
      if (key === 'paste') {
        this.pasteFromClipboard();
      }
      this.close();
    },
    async pasteFromClipboard() {
      if (window.isSecureContext) {
        // 请求剪贴板读取权限
        navigator.clipboard
          .readText()
          .then((text) => {
            this.pasterContent(text);
          })
          .catch((err) => {
            Message.error("无法读取剪贴板内容: " + String(err));
          });
      } else {
        Message.warning("当前环境不支持剪贴板直接读取，请手动粘贴操作");
        this.$refs.pasteContextRef.open();
      }
    },
    pasterContent(text) {
      try {
        const item = JSON.parse(text);
        if (
          _.isObject(item) &&
          _.has(item, "type") &&
          _.has(item, "formData")
        ) {
          item.cid = nanoid();
          item.formData.notMod = false;
          this.dataObj.pageData.push(item);
        } else if (
          _.isArray(item) &&
          item.every(
            (e) => _.isObject(e) && _.has(e, "type") && _.has(e, "formData")
          )
        ) {
          item.forEach((e) => {
            e.cid = nanoid();
            e.formData.notMod = false;
            this.dataObj.pageData.push(e);
          });
        } else {
          Message.error("剪贴板内容不是有效的组件数据");
        }
      } catch (e) {
        Message.error("剪贴板内容不是有效的组件数据");
      }
    },
  },
  mounted() {
    this.calculateScreenScale();
  },
};
</script>

<style lang="less" scoped>
/* 右键菜单的基本样式 */
.context-menu {
  background-color: #fff;
  //border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.2);
  list-style: none;
  margin: 0;
  padding: 0;
  min-width: 160px;
}

/* 菜单项的基本样式 */
.context-menu-item {
  color: #333;
  display: flex; /* 使用 Flexbox 布局 */
  align-items: center; /* 垂直居中 */
  font-size: 14px;
  padding: 8px 16px;
  text-decoration: none;
  white-space: nowrap;
  width: 100%; /* 宽度占满整个菜单 */
}

/* 鼠标悬停时的样式 */
.context-menu-item:hover {
  background-color: #e7e7e7;
  color: #000;
}

/* 当前选中的菜单项样式 */
.context-menu-item-selected,
.context-menu-item:hover {
  background-color: #007bff; /* 蓝色选中背景 */
  color: #fff; /* 选中文字颜色为白色 */
}
</style>
